package com.ah.cookie.autologin;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ah.util.Const;

@WebServlet("/ServletLoginManual")
public class C2ServletLoginManual extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String uname = request.getParameter("uname");
		String pwd = request.getParameter("pwd");
		String autologin = request.getParameter("autologin");
		System.out.println("复选框被选中的结果：" + autologin);// 选中on/未选中null

		if (C4ServiceLogin.login(uname, pwd) == true) {
			System.out.println("登录成功\r\n---");
			if ("on".equals(autologin)) {
				// 把自动登录用的Cookie，发送给浏览器
				int expiry = 60 * 60 * 24 * 7;
				
				Cookie ckUname = new Cookie("uname", uname);
				ckUname.setMaxAge(expiry);
				ckUname.setPath("/");
				response.addCookie(ckUname);
				
				Cookie ckPwd = new Cookie("pwd", pwd);
				ckPwd.setMaxAge(expiry);
				ckPwd.setPath(request.getContextPath());
				response.addCookie(ckPwd);
			}
			response.sendRedirect(Const.P_SUCCESS);
 
		} else {
			System.out.println("登录失败\r\n---");
			response.sendRedirect(Const.P_LOGIN);
		}
	}

}
